package com.sophialex.health.record.common.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class TestUtil {

	public static String[] getFileName(String path) {
		URL url;
		List<String> list = new ArrayList<String>();
		try {
			url = new URL(path);
			HttpURLConnection conn;
			conn = (HttpURLConnection) url.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			StringBuffer temp = new StringBuffer();
			String strXml;
			Reader rd = new InputStreamReader(is, "UTF-8");
			int c = 0;
			while ((c = rd.read()) != -1) {
				temp.append((char) c);
			}
			is.close();
			strXml = temp.toString();
			Document duc = DocumentHelper.parseText(strXml);
			if (duc != null) {
				Element element = duc.getRootElement();
				Iterator iterator = element.elementIterator();
				Element ele;
				while (iterator.hasNext()) {
					ele = (Element) iterator.next();
					if (ele.getName().equals("plugin")) {
						String id = ele.attributeValue("id");
						String version = ele.attributeValue("version");
						list.add(id + "_" + version + ".jar");
					}
				}
			}

		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}
		return list.toArray(new String[] {});
	}

	public static void main(String[] arg) {
		String[] strs = getFileName("http://localhost:8082/com.sophialex.health.site/features/feature.xml");
		System.out.println(strs[0]);
		HttpURLConnection hc = null;
		for (String str : strs) {
			try {
				URL url = new URL(
						"http://localhost:8082/com.sophialex.health.site/plugins/"
								+ str);
				hc = (HttpURLConnection) url.openConnection();
				// 定义输入流
				InputStream instream = hc.getInputStream();
				// 创建这个文件输出流
				FileOutputStream fos = new FileOutputStream("E:\\temp"
						+ File.separator + str);
				// 定义一个大小为1024的字节数组
				byte[] buf = new byte[10240000];
				// 从输入流中读出字节到定义的字节数组
				int len = instream.read(buf, 0, 10240000);
				// 循环读入字节，然后写到文件输出流中
				while (len != -1) {
					fos.write(buf, 0, len);
					len = instream.read(buf, 0, 10240000);
				}
				fos.flush();
				fos.close();
			} catch (Exception e) {
			} finally {
				if (hc != null)
					hc.disconnect();
			}
		}
	}
}
